#include <iostream>
#include "Worker.h"

using namespace std;

WorkerImp::WorkerImp(EventProcessor& _master, DistributedCounter& _dCounter)
: dCounter(_dCounter)
#ifdef DEBUG_EVPROC
: EventProcessorImp(true, "Worker") // comment to remove debug
#endif
{
  	Master.CopyFrom(_master);	
  	RegisterMessageProcessor(AddMessage::type, &AddThis, 1 /*priority*/);
  	RegisterMessageProcessor(DieMessage::type, &Die, 0 /*priority*/);
  	
	RegisterMessageProcessor(GenDoneMessage::type, &GenDone, 2 /*priority*/);
	SendReady();	
	//cout<<"Worker Ready - Worker"<<endl;
}

void WorkerImp::SendReady(){

	EventProcessor myInterfClone;
	myInterfClone.CopyFrom(myInterface);

	ReadyMessage_Factory(Master, 0, myInterfClone);
}

void WorkerImp::SendTheSum(vector<int>& subset, int start){
	
	vector<int>::iterator xit;	
	long int xSum = 0;
	for(xit = subset.begin()+start;xit < subset.begin()+start+10;++xit){
		xSum += *xit;
	}

	EventProcessor myInterfClone;
	myInterfClone.CopyFrom(myInterface);	
	
	//cout<<"The sum here is - Worker  "<<xSum<<endl;	
	DoneMessage_Factory(Master, xSum, myInterfClone);

}

MESSAGE_HANDLER_DEFINITION_BEGIN(WorkerImp, GenDone, GenDoneMessage)
	
	evProc.generatorsDone = true;	
 
MESSAGE_HANDLER_DEFINITION_END

MESSAGE_HANDLER_DEFINITION_BEGIN(WorkerImp, AddThis, AddMessage)  

	//cout<<"The message received is "<<endl;
	evProc.SendTheSum(msg.buffer, msg.start);

	sleep(1);
	//if(evProc.generatorsDone)
	{

		if(evProc.dCounter.Decrement(1) == 0){
			cout<<"I am the final Worker "<<endl;
			KillEvProc(evProc.Master);
		}
	}
	evProc.Seppuku();

MESSAGE_HANDLER_DEFINITION_END

MESSAGE_HANDLER_DEFINITION_BEGIN(WorkerImp, Die, DieMessage) 
	
	evProc.EventProcessorImp::processDieMessage(evProc,msg);
	 
MESSAGE_HANDLER_DEFINITION_END
